import os
import time
from srt.handler import Srt
from srt.styles import STYLES
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *


class PathWindonw(QWidget):

    def __init__(self,path):
        super(PathWindonw,self).__init__()
        self.path = path
        self.setStyleSheet(STYLES.COLOR_STYLES)
        self.setWindowTitle('输出路径')
        self.setMaximumWidth(800)
        self.setFixedHeight(150)
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(20)
        self.main_layout.setAlignment(Qt.AlignCenter)
        self.path_label = QLabel(path)
        self.path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.path_btn = QPushButton('点击打开目录')
        self.path_btn.setStyleSheet(STYLES.BTN_STYLE_S)
        self.path_btn.clicked.connect(self._show_dir)
        self.main_layout.addWidget(self.path_label)
        self.main_layout.addWidget(self.path_btn)
        self.setLayout(self.main_layout)

    def _show_dir(self):
        try:
            os.startfile(os.path.dirname(self.path))
        except Exception as start_ERR:
            pass

    
class TranslateThread(QThread):
    count_Signal = Signal(float)
    text_Signal = Signal(str)
    def __init__(self,srt_handlder):
        super(TranslateThread, self).__init__()
        self.srt_handler = srt_handlder
        self.data_list = self.srt_handler.data_list()
        self.rows = self.srt_handler.rows()
        self.pure_data,self.cliped_data = self.srt_handler.get_cliped_data()
        self.row_line_list = [f'{i+1}\n' for i in range(self.rows)]
        self.all_count = len(self.cliped_data)
        self.translated_list = []


    def run(self):
        
        index=0
        for i in self.cliped_data:
            st = '\n'.join(i)
            data = self.srt_handler.translate(st)
            self.translated_list.extend(data)
            index+=1
            self.count_Signal.emit(index*1.0/self.all_count)
            time.sleep(1.3)
        if index == self.all_count:
            keys = sorted(list(self.pure_data.keys()))
            for k in range(len(keys)):
                key = keys[k]
                self.data_list[key] = self.translated_list[k]
            text = ''.join(self.data_list)
            self.text_Signal.emit(text)


class TranslateWin(QWidget):

    def __init__(self,parent=None):
        super(TranslateWin,self).__init__(parent)

        self.setStyleSheet(STYLES.COLOR_STYLES)
        self.setWindowTitle('CGAI-SRT')

        self.main_layout = QHBoxLayout()
        
        self.srt_layout = QVBoxLayout()
        self.srt_tool_layout = QHBoxLayout()
        self.srt_tool_layout.setContentsMargins(0,0,0,10)
        self.srt_edit = QLineEdit()
        self.select_btn = QPushButton('选择srt')
        self.select_btn.clicked.connect(self._select_srt)
        self.select_btn.setFixedWidth(80)
        self.select_btn.setStyleSheet(STYLES.BTN_STYLE_B)
        self.srt_btn = QPushButton('载入srt')
        self.srt_btn.setFixedWidth(80)
        self.srt_btn.clicked.connect(self._import_srt)
        self.srt_btn.setStyleSheet(STYLES.BTN_STYLE_B)
        self.srt_tool_layout.addWidget(self.srt_edit)
        self.srt_tool_layout.addWidget(self.select_btn)
        self.srt_tool_layout.addWidget(self.srt_btn)
        self.srt_text = QTextBrowser()
        self.srt_text.verticalScrollBar().valueChanged.connect(self._vchange)
        self.srt_layout.addLayout(self.srt_tool_layout)
        self.srt_layout.addWidget(self.srt_text)

        self.translate_layout = QVBoxLayout()
        self.translate_tool_layout = QHBoxLayout()
        self.translate_tool_layout.setSpacing(20)
        self.translate_btn = QPushButton('翻译')
        self.translate_btn.clicked.connect(self._translate)
        self.translate_btn.setFixedWidth(80)
        self.translate_btn.setStyleSheet(STYLES.BTN_STYLE_B)
        self.export_btn = QPushButton('输出srt')
        self.export_btn.clicked.connect(self._export_srt)
        self.export_btn.setFixedWidth(80)
        self.export_btn.setStyleSheet(STYLES.BTN_STYLE_B)
        self.translate_tool_layout.addWidget(self.translate_btn)
        self.translate_tool_layout.addWidget(self.export_btn)
        self.translate_progress = QLabel('')
        self.translate_progress.setFixedSize(0,4)
        self.translate_progress.setStyleSheet(STYLES.PLAYED_COLOR)
        self.translate_text = QTextEdit()
        self.translate_text.verticalScrollBar().valueChanged.connect(self._vchange)
        self.translate_layout.addLayout(self.translate_tool_layout)
        self.translate_layout.addWidget(self.translate_progress)
        self.translate_layout.addWidget(self.translate_text)

        self.main_layout.addLayout(self.srt_layout)
        self.main_layout.addLayout(self.translate_layout)
        self.setLayout(self.main_layout)

        self.srt_handler = None  # 翻译handler
        self.translate_thread = None 


    def _select_srt(self):
        """
        选择srt
        """
        openfile_name = QFileDialog.getOpenFileName(self,'选择srt文件','','SRT(*.srt ; *.SRT)')
        if openfile_name:
            self.srt_edit.setText(openfile_name[0])

    def _import_srt(self):
        """
        导入srt
        """
        self.srt_handler = None 
        srt_path = self.srt_edit.text()
        if not os.path.exists(srt_path):
            QMessageBox.information(None,'错误','该文件不存在')
            return
        srt_handler = Srt(srt_path)
        self.srt_text.setText(srt_handler.raw_data())
        self.translate_text.setText(srt_handler.raw_data())
        self.srt_handler = srt_handler


    def _vchange(self,value):
        self.srt_text.verticalScrollBar().setValue(value)
        self.translate_text.verticalScrollBar().setValue(value)


    def _translate(self):


        self.translate_progress.setFixedWidth(0)
        self.translate_text.clear()
        if self.translate_thread:
            self.translate_thread.quit()
            self.translate_thread.wait()
        if self.srt_handler:
            self.translate_thread =  TranslateThread(self.srt_handler)
            self.translate_thread.count_Signal.connect(self._change_progress)
            self.translate_thread.text_Signal.connect(self._show_translation)
            self.translate_thread.start()

            
    def _change_progress(self,value): 
        L = self.translate_text.width()
        show_length = value*L
        self.translate_progress.setFixedWidth(show_length)

    def _show_translation(self,text):
        self.translate_text.setText(text)
        if self.translate_thread:
            self.translate_thread.quit()
            self.translate_thread.wait()


    def _export_srt(self):
        """
        输出srt
        """
        fileName = QFileDialog.getSaveFileName(None,"选择srt输出", ".", "srt(*.srt)")
        if fileName:
            text = self.translate_text.toPlainText()
            with open(fileName[0],'w',encoding='utf8') as w:
                w.write(text)
            if os.path.exists(fileName[0]):
                self.path_win = PathWindonw(fileName[0])
                self.path_win.show()

